package com.tedu.food.common.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tedu.food.sys.dao.MemberDao;
import com.tedu.food.sys.entity.Member;

@Service
public class ShiroUserRealm extends AuthorizingRealm{
	@Autowired
	private MemberDao memberDao;
//	@Override
//	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//		// TODO Auto-generated method stub
//		//构建凭证匹配对象
//		HashedCredentialsMatcher cMatcher=
//				new HashedCredentialsMatcher();
//		//设置加密算法
//		cMatcher.setHashAlgorithmName("MD5");
//		//设置加密次数
//		cMatcher.setHashIterations(1);
//		super.setCredentialsMatcher(cMatcher);
//	}

	@Override
	public CredentialsMatcher getCredentialsMatcher() {
		//构建凭证匹配对象
		HashedCredentialsMatcher cMatcher=
		new HashedCredentialsMatcher();
		//设置加密算法
		cMatcher.setHashAlgorithmName("MD5");
		//设置加密次数
		cMatcher.setHashIterations(1);
		return cMatcher;
	}
	/**
	 * 通过此方法获取用户认证信息,并进行封装,然后返回给
	 *SecurityManager对象
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
	   AuthenticationToken token) throws AuthenticationException {
		//1.获取用户登录时提交用户信息
		UsernamePasswordToken uToken=
		(UsernamePasswordToken)token;
		String username=uToken.getUsername();
		//2.基于用户名查找用户
		Member user=
		memberDao.findMemberByUsername(username);
		//3.判定用户是否存在
		if(user==null)
			throw new UnknownAccountException();
		
		//5.封装认证信息
		ByteSource credentialsSalt=
		ByteSource.Util.bytes(user.getSalt());
		SimpleAuthenticationInfo info=
		new SimpleAuthenticationInfo(
				user,//principal 用户身份
				user.getPassword(),//hashedCredentials
				credentialsSalt, //credentialsSalt
				getName());//realmName
		return info;//返回给SecurityManager
	}
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}
	

}









